package com.appkubes.fintech.restful.application.user.domain.impl;

import com.appkubes.fintech.core.po.*;
import com.appkubes.fintech.restful.application.afu.dao.AFuDao;
import com.appkubes.fintech.restful.application.afu.dao.AFuFuradDao;
import com.appkubes.fintech.restful.application.afu.entity.AFuFraudDto;
import com.appkubes.fintech.restful.application.afu.entity.BaseAfuDto;
import com.appkubes.fintech.restful.application.afu.service.AFuService;
import com.appkubes.fintech.restful.application.credit.dao.CreditDao;
import com.appkubes.fintech.restful.application.credit.service.CreditService;
import com.appkubes.fintech.restful.application.user.dao.UserBaseInfoDao;
import com.appkubes.fintech.restful.application.user.dao.UserDao;
import com.appkubes.fintech.restful.application.user.domain.UserCertificateDomain;
import com.appkubes.fintech.restful.application.user.service.UserService;
import com.google.gson.Gson;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户认证表 服务实现类
 * </p>
 *
 * @author rongjie
 * @since 2020-01-04
 */
@SuppressWarnings("ALL")
@Service
@Slf4j
@Data
public class UserCertificateDomainImpl implements UserCertificateDomain {

    @Resource
    UserDao userDao;

    @Resource
    CreditService creditService; //信用额度服务
    @Resource
    UserBaseInfoDao baseInfoDao;
    @Resource
    UserService userService;

    @Resource
    AFuService afService;

    @Resource
    AFuDao aFuDao;

    @Resource
    AFuFuradDao aFuFuradDao;


    @Autowired
    CreditDao creditDao;

    /**
     * 基本信息
     *
     * @param userKey
     * @param isBaseInfo
     * @return
     */
    @Override
    public Integer updateBaseInfoCertificate(String userKey, Integer isBaseInfo) {
        FintechUser user = getFintechUser(userKey);
        user.setIsBaseInfo(isBaseInfo);
        Integer effectRow = 0;
        effectRow += userDao.updateByPrimaryKeySelective(user);
//        creditService.addCredit(user.getUserKey(), 100000L); //每添加1个，增加1000的额度
        effectRow += validateCertificate(user);
        return effectRow;
    }

    /**
     * 工作认证
     *
     * @param userKey
     * @param isJob
     * @return
     */
    @Override
    public Integer updateJobCertificate(String userKey, Integer isJob) {
        FintechUser user = getFintechUser(userKey);
        user.setIsJob(isJob);
        Integer effectRow = 0;
        effectRow += userDao.updateByPrimaryKey(user);
//        creditService.addCredit(user.getUserKey(), 100000L); //每添加1个，增加1000的额度
        effectRow += validateCertificate(user);
        return effectRow;
    }

    /**
     * 紧急联系人
     *
     * @param userKey
     * @param isEmergency
     * @return
     */
    @Override
    public Integer updateContactCertificate(String userKey, Integer isEmergency) {
        FintechUser user = getFintechUser(userKey);
        user.setIsEmergency(isEmergency);
        Integer effectRow = 0;
        effectRow += userDao.updateByPrimaryKey(user);
//        creditService.addCredit(user.getUserKey(), 100000L); //每添加1个，增加1000的额度
        effectRow += validateCertificate(user);
        return effectRow;
    }

    /**
     * 实名认证
     *
     * @param userKey
     * @param personalStatus : 1:上传身份证照, 2:人脸识别
     * @return
     */
    @Override
    public Integer updatePersonalCertificate(String userKey, Integer personalStatus) {
        Integer effectRow = 0;
        FintechUser user = getFintechUser(userKey);
        user.setIsRealNameCertificate(personalStatus);
        effectRow += userDao.updateByPrimaryKey(user);
//        creditService.addCredit(user.getUserKey(), 100000L); //每添加1个，增加1000的额度
        effectRow += validateCertificate(user);
        return effectRow;
    }

    /**
     * 银行卡认证
     *
     * @param userKey
     * @param bankCardCertificate
     * @return
     */
    @Override
    public Integer updateBankCardCertificate(String userKey, Integer bankCardCertificate) {
        Integer effectRow = 0;
        FintechUser user = getFintechUser(userKey);
        user.setIsBankCardCertificate(bankCardCertificate);
        if (bankCardCertificate.equals(1)) {
            //只要银行卡认证成功就认为是运营商也认证成功
            user.setIsOperatorGet(1);
        }
        log.info("begin update bank, userKey is {}", userKey);
        System.out.println("begin update bank, userKey is " + userKey);
        effectRow += userDao.updateByPrimaryKey(user);
        log.info("end update bank,userKey is {},effectRow is {}", userKey, effectRow);
        System.out.println("end update bank,userKey is " + userKey + ",effectRow is " + effectRow);
//        creditService.addCredit(user.getUserKey(), 100000L); //每添加1个，增加1000的额度
        effectRow += validateCertificate(user);
        log.info("end update bank,userKey is {},effectRow2 is {}", userKey, effectRow);
        System.out.println("end update bank,userKey is " + userKey + ",effectRow2 is " + effectRow);
        return effectRow;
    }

    //获取当前的用户
    FintechUser getFintechUser(String userKey) {
        FintechUser user = userDao.selectByPrimaryKey(userKey);
        if (user == null) {
            //补偿基础数据缺失
            user = new FintechUser();
            user.setUserKey(userKey);
            userDao.insertSelective(user);
            user = userDao.selectByPrimaryKey(userKey);//需要使用数据库的默认值进行重新初始化
        }
        return user;
    }

    /**
     * 基础信息验证
     *
     * @param userKey
     * @return
     */
    @Transactional
    Integer validateCertificate(String userKey) {
        {
            FintechUser user = userDao.selectByPrimaryKey(userKey);
            if (user == null) {
                //补偿基础数据缺失
                user = new FintechUser();
                userDao.insertSelective(user);
            }
            return validateCertificate(user);
        }
    }

    @Transactional
    public Integer validateCertificate(FintechUser user) {
        BaseAfuDto afu = null;
        AFuFraudDto aFuFraudDto = null;
        Integer effectRow = 0;
        if (user.getIsBaseInfo() > 0 && user.getIsJob() > 0 && user.getIsEmergency() > 0) {
            //如果基础信息的三项均已经认证，则设置汇总已经认证
            user.setIsBaseInfoCertificate(1);
            effectRow += userDao.updateByPrimaryKey(user);
//            creditService.addCredit(user.getUserKey(), 100000L); //每添加1个，增加1000的额度
        }
        if (user.getIsBaseInfoCertificate() > 0
                && user.getIsRealNameCertificate() > 1
                && user.getIsBankCardCertificate() > 0
                && user.getIsOperatorGet() > 0
        ) {
            if (null == afService) {
                log.error("afu: {}", "----------------service ==null-------------------------");
            } else {
                log.error("afu: {}", "----------------coming-------------------------");
                afu = afService.getAFuData(user.getUserKey());
                if (afu.getSuccess() == true && "10000".equals(afu.getCode())) {
                    log.error("afu: {}", "----------------coming- 阿福分------------------------");
                    FintechDataAfu fintechDataAfu = new FintechDataAfu();
                    fintechDataAfu.setAppKey("123");
                    fintechDataAfu.setUserKey(user.getUserKey());
                    fintechDataAfu.setCompositeScore(afu.getData().getCompositeScore());
                    fintechDataAfu.setDecisionSuggest(afu.getData().getDecisionSuggest());
                    try {
                        aFuDao.insert(fintechDataAfu);
                        FintechUserBaseInfo fintechUserBaseInfo = baseInfoDao.selectByPrimaryKey(user.getUserKey());
                        fintechUserBaseInfo.setCompositeScore(fintechDataAfu.getCompositeScore());
                        fintechUserBaseInfo.setDecisionSuggest(fintechDataAfu.getDecisionSuggest());
                        baseInfoDao.updateByPrimaryKey(fintechUserBaseInfo);
                    } catch (Exception e) {
                        log.error("afu: {}", "----------------coming- 阿福分 插入失败------------------------");
                        e.printStackTrace();
                    }
                }
                aFuFraudDto = afService.getAFuFRUADData(user.getUserKey());
                log.error("afu: {}", "----------------coming- 欺 ------------------------");
                if (aFuFraudDto.isSuccess() && "10000".equals(aFuFraudDto.getCode())) {
                    log.error("afu: {}", "----------------coming- 欺诈 ------------------------");
                    FintechDataAfuFruad fintechDataAfuFruad = new FintechDataAfuFruad();
                    fintechDataAfuFruad.setAppKey("123");
                    fintechDataAfuFruad.setUserKey(user.getUserKey());
                    fintechDataAfuFruad.setData(new Gson().toJson(aFuFraudDto.getData()));
                    try {
                        aFuFuradDao.insert(fintechDataAfuFruad);
                    } catch (Exception e) {
                        log.error("afu: {}", "----------------coming- 欺诈插入失败 ------------------------");
                        e.printStackTrace();
                    }
                    try {
                        if (null != aFuFraudDto && null != aFuFraudDto.getData() && ("5".equals(aFuFraudDto.getData().getFraudLevel()) || "4".equals(aFuFraudDto.getData().getFraudLevel()))) {
                            rejectUser(user.getUserKey(), "自动拒绝--命中：阿福欺诈，阿福等级为" + aFuFraudDto.getData().getFraudLevel() + "级。");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            //如果4大项均已经认证，则认为所有的认证状态通过
            if (user.getIsAllCertificate() != 1) {
                user.setIsAllCertificateEndTime(new Date());
                user.setIsAllCertificate(1);
                effectRow += userDao.updateByPrimaryKey(user);
                try {
                    log.info("updateStatisAuthCount userkey is {}", user.getUserKey());
                    System.out.println("updateStatisAuthCount userkey is " + user.getUserKey());
                    userService.updateStatisAuthCount(user.getUserKey());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

//            creditService.addCredit(user.getUserKey(), 100000L); //每添加1个，增加1000的额度

        }
        return effectRow;

    }

    public FintechCredit rejectUser(String userKey, String rejectReason) {
        FintechCreditExample example = new FintechCreditExample();
        example.createCriteria().andUserKeyEqualTo(userKey);
        List<FintechCredit> creditList = creditDao.selectByExample(example);
        if (null == creditList || creditList.size() < 1) {
            return null;
        }
        FintechCredit credit = creditList.get(0);
        credit.setCreditStatus(2);
        credit.setUpdateTime(new Date());
        credit.setApproval(rejectReason);
        creditDao.updateByPrimaryKey(credit);
        return credit;
    }
}
